package com.sagereal.wtc.factorymode.Activity;

import android.content.BroadcastReceiver;
import android.database.ContentObserver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.provider.Settings;
import android.widget.Button;
import android.widget.Toast;

import com.sagereal.wtc.factorymode.R;

public class ReceiverActivity extends BaseActivity {
    private Button mTestPass,mTestFail;
    private MediaPlayer mMediaPlayer;
    private BroadcastReceiver mScreenReceiver,mHeadsetReceiver;
    private VolumeObserver mVolumeObserver;
    private Handler mHandler;
    private Runnable mPlayRunnable;
    private AudioManager mAudioManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_receiver);
        setTitle(getString(R.string.title_receiver_test));

        mTestPass = findViewById(R.id.test_pass);
        mTestFail = findViewById(R.id.test_fail);
        mHandler = new Handler();
        mPlayRunnable = this::startPlaying;
        mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
        mAudioManager.setStreamVolume(AudioManager.STREAM_VOICE_CALL, 11, AudioManager.FLAG_REMOVE_SOUND_AND_VIBRATE);
        initView();
        registerVolumeObserver();
        registerScreenReceiver();
    }

    private void initView() {
        //测试通过
        mTestPass.setOnClickListener(v -> {
            Intent intent = new Intent(ReceiverActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1)); // 获取启动该Activity时传递的ItemId
            intent.putExtra("status", "pass");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK , intent);
            finish();
        });

        //测试失败
        mTestFail.setOnClickListener(v -> {
            Intent intent = new Intent(ReceiverActivity.this, ItemTestActivity.class);
            intent.putExtra("ItemId", getIntent().getIntExtra("ItemId", -1)); // 获取启动该Activity时传递的ItemId
            intent.putExtra("status", "fail");
            intent.putExtra("check", getIntent().getStringExtra("check"));
            setResult(RESULT_OK , intent);
            finish();
        });
        startPlaying();
    }

    private void startPlaying() {
        setEarpieceMode(true);
        if (mMediaPlayer == null) {
            mMediaPlayer = MediaPlayer.create(this, R.raw.sound); // 确保在 res/raw 文件夹中有一个 sound.mp3 文件
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.start();
        }else {
            mMediaPlayer.reset();  // 重置播放器状态
            mMediaPlayer.setAudioStreamType(AudioManager.STREAM_VOICE_CALL);  // 确保音频流类型正确
            mMediaPlayer = MediaPlayer.create(this, R.raw.sound);
            mMediaPlayer.setLooping(true);
            mMediaPlayer.start();
        }
        updateVolume();
    }
    private void stopPlaying() {
        setNormalMode(true);
        if (mMediaPlayer != null) {
            if(mMediaPlayer.isPlaying()){
                mMediaPlayer.stop();
            }
            mMediaPlayer.release();
            mMediaPlayer = null;
        }
    }
    private void updateVolume() {
        int currentCallVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_VOICE_CALL);
        int maxCallVolume = mAudioManager.getStreamMaxVolume(AudioManager.STREAM_VOICE_CALL);
//        float volume = (float) currentCallVolume / maxCallVolume;
//        mMediaPlayer.setVolume(volume, volume);
        if (mMediaPlayer != null) {
            if (maxCallVolume > 0) {
                float volume = (float) currentCallVolume / maxCallVolume;
                mMediaPlayer.setVolume(volume, volume);
            } else {
                mMediaPlayer.setVolume(0f, 0f);
            }
        }
    }

    private void setEarpieceMode(boolean enabled) {
        mAudioManager.setMode(AudioManager.MODE_IN_COMMUNICATION);
        mAudioManager.setSpeakerphoneOn(!enabled);
    }

    private void setNormalMode(boolean enabled) {
        mAudioManager.setMode(AudioManager.MODE_NORMAL);
        mAudioManager.setSpeakerphoneOn(!enabled);
    }

    private void registerVolumeObserver() {
        mVolumeObserver = new VolumeObserver(new Handler());
        getContentResolver().registerContentObserver(Settings.System.CONTENT_URI, true, mVolumeObserver);
    }

    private class VolumeObserver extends ContentObserver {
        VolumeObserver(Handler handler) {
            super(handler);
        }
        @Override
        public void onChange(boolean selfChange) {
            super.onChange(selfChange);
            updateVolume();  // 实时更新 MediaPlayer 音量
        }
    }
    private void registerScreenReceiver() {
        mScreenReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
                    mHandler.removeCallbacks(mPlayRunnable);
                    stopPlaying();
                } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
                    mHandler.post(mPlayRunnable);
                }
            }
        };
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        filter.addAction(Intent.ACTION_SCREEN_ON);
        registerReceiver(mScreenReceiver, filter);
    }

    private void registerHeadsetReceiver() {
        mHeadsetReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
                    int state = intent.getIntExtra("state", -1);
                    switch (state) {
                        case 0:
                            // 耳机未插入
                            startPlaying();
                            mTestPass.setEnabled(true);
                            break;
                        case 1:
                            // 耳机插入
                            stopPlaying();
                            Toast.makeText(context, R.string.headset_out, Toast.LENGTH_SHORT).show();
                            mTestPass.setEnabled(false);
                            break;
                    }
                }
            }
        };
        IntentFilter filter = new IntentFilter(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(mHeadsetReceiver, filter);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
            setEarpieceMode(true);
            startPlaying();
        } else {
            stopPlaying();
            setNormalMode(true);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        setEarpieceMode(true);
        registerHeadsetReceiver();
        startPlaying();
    }
    @Override
    protected void onPause() {
        setNormalMode(true);
        super.onPause();
        stopPlaying();
        unregisterReceiver(mHeadsetReceiver);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        setNormalMode(true);
        unregisterReceiver(mScreenReceiver);
        stopPlaying();
        getContentResolver().unregisterContentObserver(mVolumeObserver);
    }
}